from datetime import date, timedelta

from django.db import connection
from django.shortcuts import render, redirect
from django.contrib import messages

from order.models import Orders, Orderproduct
from .models import Cartproduct
from products.models import Products
from users.models import Users

import random

from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from rest_framework.views import APIView
# Create your views here.
from rest_framework import viewsets

from utils.serializers import ProductSerializer
from .models import Products
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.core.serializers import serialize
import json
from django import forms

def create_order_product(orderid, product, cartproducts):
    # 获取数据库连接
    with connection.cursor() as cursor:
        # 构建 SQL 插入语句
        sql = """
        INSERT INTO Orderproduct (orderid, productid, number)
        VALUES (%s, %s, %s)
        """
        # 执行 SQL 插入语句
        cursor.execute(sql, [
            orderid,
            product.productid,
            cartproducts.count
        ])
        # 提交事务
        connection.commit()
def create_order(orderid, userid, itemcount, total_amount, actual_payment):
    # 获取数据库连接
    with connection.cursor() as cursor:
        # 构建 SQL 插入语句
        sql = """
        INSERT INTO Orders (orderid, userid, payment_method, order_time, transaction_time, itemcount, payment_time, expected_delivery_date, total_amount, actual_payment, order_status)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        """
        # 计算预计发货日期
        expected_delivery_date = date.today() + timedelta(days=1)
        # 执行 SQL 插入语句
        cursor.execute(sql, [
            orderid,
            userid,
            '01',  # 支付方式，假设为'01'表示某种支付方式
            date.today(),  # 订单时间，假设为今天
            date.today(),  # 交易时间，假设为今天
            itemcount,  # 商品数量
            date.today(),  # 支付时间，假设为今天
            expected_delivery_date,  # 预计发货日期
            total_amount,  # 总金额
            actual_payment,  # 实际支付金额
            '01'  # 订单状态，假设为'01'表示某种状态
        ])
        # 提交事务
        connection.commit()

class CartProfileForm(forms.Form):
    productid = forms.CharField(required=False, label='商品ID')

class Cart(APIView):
    def get(self, request):
        form = CartProfileForm(request.POST)
        return render(request, 'cart.html', {'form': form})


    def post(self, request):
        form = CartProfileForm(request.POST)
        userid=request.session.get('userid')
        user=Users.objects.get(userid=userid)
        cartid=userid
        if form.is_valid():
            product_id = form.cleaned_data['productid']
            action = request.POST.get('action')
            #加入购物车
            if action == '1':
                try:
                    product_instance = Products.objects.get(productid=product_id)
                    try :
                        new = Cartproduct.objects.get(cartid=cartid,productid=product_instance)
                        new.count = new.count + 1
                        with connection.cursor() as cursor:
                            # 构建 SQL 语句
                            sql = """
                            UPDATE Cartproduct
                            SET count = count + 1
                            WHERE cartid = %s AND productid = %s
                            """
                            # 执行 SQL 语句
                            cursor.execute(sql, [cartid, product_instance.productid])
                            # 提交事务
                            connection.commit()
                        # new2=[new.cartid,new.productid,new.count+1]
                        # new.delete()
                        # new3=Cartproduct.objects.create(cartid=new2[0],productid=new2[1],count=new2[2])

                    except :
                        new_Cartproduct = Cartproduct.objects.create(
                            cartid=cartid,
                            productid=product_instance,
                            count=1,
                            userid=user,
                            )
                    return HttpResponse("加入购物车成功")
                except :
                    return HttpResponse("商品不存在")
            elif action == '2':
                try:
                    Cartproduct.objects.filter(productid=product_id).delete()
                    messages.success(request, "商品删除成功")
                    return redirect('/cart/')
                except Exception as e:
                    return HttpResponse("删除失败：" + str(e), status=400)
            # elif action == '3':
            #     #####查询购物车中所有商品
            #     retutn
            elif action == '4':

                if product_id:
                    returnproducts=[]
                    products = Cartproduct.objects.filter(productid=product_id)
                    for product in products:
                        pro = Products.objects.get(productid=product.productid.productid)
                        returnproducts.append({
                            'productid': product.productid,
                            'count': product.count,
                            'price': pro.price,
                        })
                    return render(request, 'cart.html', {'products': returnproducts, 'form': form})
                return HttpResponse("请输入id", status=400)
            elif action == '5':
                ###购物车下单create order
                cartproductss = Cartproduct.objects.filter(cartid=cartid)
                itemcount=Cartproduct.objects.filter(cartid=cartid).count()
                orderid=str(random.randint(0, 9999)),
                total_amount =0
                actual_payment=0
                for cartproducts in cartproductss:
                    product = Products.objects.get(productid=cartproducts.productid.productid)
                    total_amount+=cartproducts.count*product.price
                    create_order_product(orderid, product, cartproducts)
                    if(cartproducts.count==2):
                        actual_payment+=cartproducts.count*product.price*0.8
                    elif (cartproducts.count >= 3):
                        actual_payment += cartproducts.count * product.price * 0.75
                    else:
                        actual_payment+=cartproducts.count*product.price
                create_order(orderid, userid, itemcount, total_amount, actual_payment)

                return HttpResponse("订单创建成功")
            elif action == '6':
                cartproducts = Cartproduct.objects.filter(cartid=cartid)
                itemcount=Cartproduct.objects.filter(cartid=cartid).count()
                total_amount =0
                actual_payment=0
                for cartproduct in cartproducts:
                    product = Products.objects.get(productid=cartproduct.productid.productid)
                    total_amount+=cartproduct.count*product.price
                    if(cartproduct.count==2):
                        actual_payment+=cartproduct.count*product.price*0.8
                    elif(cartproduct.count>2):
                        actual_payment+=cartproduct.count*product.price*0.75
                    else:
                        actual_payment+=cartproduct.count*product.price

                returnproducts = []
                products = Cartproduct.objects.filter(cartid=cartid)
                for product in products:
                    pro = Products.objects.get(productid=product.productid.productid)
                    returnproducts.append({
                        'productid': product.productid,
                        'count': product.count,
                        'price': pro.price,
                    })
                returnall={'itemcount':itemcount,'total_amount':total_amount,'actual_payment':actual_payment}
                return render(request, 'cart.html', {'products': returnproducts, 'form': form, 'returnall': returnall})

            else:
                return HttpResponse("未知操作", status=400)
        else:
            messages.error(request, "表单数据有误，请检查后重新提交")
            return render(request, 'cart.html', {'form': form})

'''

    cartid = models.CharField(db_column='cartid', primary_key=True, max_length=5)  # Field name made lowercase.
    productid = models.ForeignKey(Products, models.DO_NOTHING, db_column='productid', blank=True, null=True)  # Field name made lowercase.
    userid = models.ForeignKey(Users, models.DO_NOTHING, db_column='userid', blank=True, null=True)  # Field name made lowercase.
    cpstatus = models.CharField(db_column='cpstatus', max_length=3, blank=True, null=True)  # Field name made lowercase.
    count=models.IntegerField(db_column='count', blank=True, null=True)

'''

